import { getToken } from '@/common/auth'
const sha256 = require('js-sha256').sha256

/**
 * author：郭计腾
 * post请求加密算法
 */
const blackList = ['login'] // 请求白名单,如果存在的话 则不加密 /admin/user/getToken
export function resPost(data, obj, type) { // type 1: 不使用异或加密  2： 使用异或加密
  const config = data
  if (blackList.indexOf(config.url) == -1) {
    const sjzfc = randomString()
    if (type === 2) {
      obj = {
        params: xorjiami(obj, sjzfc)
      }
      if (config.method === 'get') {
        config.params = obj
      } else {
        config.data = obj
      }
    }
    let NEWAESlist = ''
    if (localStorage.getItem('NEWAES') != null && localStorage.getItem('NEWAES') != undefined) {
      NEWAESlist = localStorage.getItem('NEWAES').split(',')
    }
    let encyStr = ''
    if (obj != null) {
      const ascObj = objKeySort(obj) // 把对象排序
      var count = 0 // 对象属性的个数
      for (const i in ascObj) {
        if (ascObj.hasOwnProperty(i)) {
          count++
        }
      }
      let index = 0
      for (const key in ascObj) {
        index += 1
        encyStr += key + '=' + ascObj[key] || ''
        if (index != count) {
          encyStr += '|'
        }
      }
    }
    if (!getToken()) {
      NEWAESlist = ''
    }
    /**
     * 保证所有接口都必须校验签名，由于token过期后后端获取不到对应的key和iv导致验签失败，所以增加一个不带key和iv的签名
     */
      // 带key和iv的签名
    const bwqm1 = encyStr + ':' + (getToken() || '') + ':' + sjzfc + ':' + NEWAESlist || ''
    // 不带key和iv的签名
    const bwqm2 = encyStr + ':' + (getToken() || '') + ':' + sjzfc + ':' + ''
    config.headers['ttsxyhcs'] = getToken() || ''
    config.headers['ttsxsjzc'] = sjzfc
    config.headers['ttsxbwqm'] = sha256(bwqm1) + ',' + sha256(bwqm2)
  }
  return config
}

/**
 *  响应时判断是否被篡改
 * @param {*} data
 */
export function getRes(data) {
  // debugger
  if (localStorage.getItem('NEWAES') == null || localStorage.getItem('NEWAES').length == 0) {
    return true
  }
  var NEWAESlist = localStorage.getItem('NEWAES')

  const sjzfc = data.config.headers.ttsxsjzc
  let NEWKEY = NEWAESlist
  const sign = data.headers.ttsxbwqm
  const ascStr = data.data
  if (data.headers.ttsxmynk) {
    NEWKEY = data.headers.ttsxmynk
  }
  const allStr = ascStr + '|' + sjzfc + '|' + NEWKEY
  const codeStr = sha256(allStr)
  if (codeStr === sign) {
    return true
  }
  return false
}

// 生成随机字符串
function randomString(len) {
  len = len || 32
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = chars.length
  var pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

function objKeySort(obj) { // 排序的函数
  var newkey = Object.keys(obj).sort() // 先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
  var newObj = {} // 创建一个新的对象，用于存放排好序的键值对
  for (var i = 0; i < newkey.length; i++) { // 遍历newkey数组
    newObj[newkey[i]] = obj[newkey[i]] // 向新创建的对象中按照排好的顺序依次增加键值对
  }
  return newObj // 返回排好序的新对象
}

/**
 * 异或算法加密
 * @param obj
 * @returns {string}
 */
export function xorjiami(obj, key) {
  if (!obj) {
    return ''
  }
  const enKey = key || getToken()
  const result = JSON.stringify(obj)
  var yyy = ''
  for (var i = 0; i < result.length; i++) {
    var zzz = (result.charCodeAt(i) & 0xFFFF) ^ parseInt(enKey.substring(enKey.length - 4), 16)
    var sss = zzz.toString(16)
    if (sss.length == 1) { sss = '000' + sss } else if (sss.length == 2) { sss = '00' + sss } else if (sss.length == 3) { sss = '0' + sss }
    yyy += sss
  }
  return yyy
}
/**
 * 异或算法解密
 * @param obj
 * @returns {string}
 */
export function xorjiemi(str, key) {
  const enKey = key || getToken()
  var xxx = str
  var result = ''
  for (var i = 0; i < xxx.length;) {
    var code = parseInt(xxx.substring(i, i + 4), 16) ^ parseInt(enKey.substring(enKey.length - 4), 16)
    result += String.fromCharCode(code)

    i = i + 4
  }
  return result
}
